package com.wzs.controller;

import com.wzs.bean.User;
import com.wzs.bean.UserLoginLog;
import com.wzs.service.LogsService;
import com.wzs.service.UserService;

import com.wzs.utils.BGUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LogsService logsService;

    @PostMapping("/register")
    public String register(User user,Model model,HttpSession session){
        User su = (User) session.getAttribute("user");
        if(StringUtils.isEmpty(su)){
            if(userService.isExists(user)){
                model.addAttribute("error","用户名或邮箱已存在");
                return "login";
            }
            Integer id = userService.addUser(user);
            user.setUserId(id);
            session.setAttribute("user",user);
        }
        List<UserLoginLog> logs = logsService.getLogs(user.getUserId());
        model.addAttribute("logs",logs);
        return "main";
    }

    @GetMapping("/")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String login(User user, HttpServletRequest request, Model model, HttpSession session){
        User su = (User) session.getAttribute("user");
        if(StringUtils.isEmpty(su)){
            User login = userService.login(user);
            if(login==null)return "redirect:/";
            UserLoginLog log = new UserLoginLog();
            log.setLoginIp(BGUtils.getIpAddress(request));
            log.setLoginTime(BGUtils.GetTime());
            log.setUserId(login.getUserId());
            logsService.addLog(log);
            su = login;
            session.setAttribute("user",login);
        }
        List<UserLoginLog> logs = logsService.getLogs(su.getUserId());
        model.addAttribute("logs",logs);
        return "main";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }

}
